package com.zlkj.pro.core.util;

import lombok.Data;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 */
@UtilityClass
public class TreeUtil {
    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public <T extends TreeNode> List<T> build(List<T> treeNodes, Object root) {
        return treeNodes.parallelStream().filter(c -> {
            c.setChildren(treeNodes.parallelStream().filter(b -> b.getParentId().equals(c.getId())).collect(Collectors.toList()));
            return c.getParentId().equals(root);
        }).collect(Collectors.toList());
    }

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId().equals(it.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.addChildren(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }


    @Data
    public class TreeNode {
        protected Long id;
        protected Long parentId;
        private Integer sort;
        protected List<TreeNode> children = new ArrayList<>();

        public void addChildren(TreeNode treeNode) {
            children.add(treeNode);
        }

        public List<TreeNode> getChildren() {
            if (children.size() <= 0) {
                return null;
            }
            return children;
        }
    }
}
